#!/usr/bin/perl -w
use strict;

#+=============================================================================+
# FILE:     matchRNA.pl
# SUMMARY:  Illustrate where results of RNAfold or CentroidFold lie 
#			compared to full sequence
# AUTHOR:   Ravi Mehra
# CREATED:  Jan. 20, 2010
# MODIFIED:
# NOTE:     Ver.1
#
# Usage: matchRNA.pl file1.pri file2.01v100 file3.01v100m8 
#
#   INPUT 1: file1.pri (fasta formated)
#   INPUT 2: file2.01v100 (blast matches)
#   INPUT 3: file3.01v100m8 (table formated) 
#
#   OUTPUT 
# 
#+=============================================================================+
#        1         2         3         4         5         6         7         8
#2345678901234567890123456789012345678901234567890123456789012345678901234567890
#+=============================================================================+


#-------------------------------------------------------------------------------
use Cwd;
#-------------------------------------------------------------------------------
# Check to make sure all three files are given
if (@ARGV < 3) {
  print " Usage: matchRNA.pl file1.pri file2.01v100 file3.01v100m8\n";
  exit(0);
}

# Open all three files for reading
my $pri_file = $ARGV[0];
open (PRI,  "<$pri_file")  || die "Cannot open $pri_file!\n";
my $blast_file = $ARGV[1];
open (BLAST,  "<$blast_file")  || die "Cannot open $blast_file!\n";
my $table_file = $ARGV[2];
open (TABLE,  "<$table_file")  || die "Cannot open $table_file!\n";

# The various hashes used
my %subjectSeqHash = ();			# Stores the Query ID and it's associated sequence from the .pri file
my %matchHash = ();					# Stores the Subject with all of it's necessary information into an array
my %queryIDSubjectHash = ();		# Stores the Query ID and it's associated Subject
my %queriesCombinedHash = ();		# Stores the Query ID with all of it's Subject matches

# read input file and main procedure
while (<PRI>) {
    # read line 
    my ($line) = $_;
    chomp ($line);
    # check the line begins with fasta tag format such as ">male_1_1"
    if ( $line =~ /^>/ ) {
        my $queryID = $line;
        $queryID = substr ($queryID, 1, length($queryID));
        # get the Sequence ID's associated sequence if eof hasn't been reached
        my $fullSequence = $_ if defined($_=<PRI>); 
        chomp ($fullSequence);
        $subjectSeqHash {$queryID} = $fullSequence;
    }
    else {
		# This should not be encountered as there should be no other lines
        print "\nMisc. Line in .pri file: ", $line;
    }
}

# read input file and main procedure
while (<BLAST>) {
    # read line 
    my ($line) = $_;
    chomp ($line);
    # check the line begins with fasta tag format such as ">male_1_1"
    if ( $line =~ /^>/ ) {
        my $subject = $line;
        $subject = substr ($subject, 1, length($subject));
        #print "Subject: ", $subject, "\n";
        # get the Sequence ID's associated sequence if eof hasn't been reached
        while (<BLAST>) {
            my ($subLine) = $_;
            chomp ($subLine);
            if ($subLine =~ /^Query:/) {
                my @queryIDLineArray = split(' ', $subLine);
                my $querySeq = $queryIDLineArray[2];
                my $querySeqStart = scalar($queryIDLineArray[1]);
                my $querySeqEnd = scalar($queryIDLineArray[3]);
                my $matches = $_ if defined($_=<BLAST>);
                chomp ($matches);
                $matches =~ s/\s+//;
                my $subjectSeqLine = $_ if defined($_=<BLAST>);
                my @subjectSeqLineArray = split(' ', $subjectSeqLine);
                my $subjectSeq = $subjectSeqLineArray[2];
                $matchHash {$subject} = [$querySeq, $querySeqStart, $querySeqEnd, 
											$matches, $subjectSeq];
                last;
            }
        }
    }
    else {
        # Other miscelaneous lines are ignored
    }
}

# read input file and main procedure
while (<TABLE>) {
    # read line 
    my ($line) = $_;
    chomp ($line);
	my @lineArray = split(' ', $line);
	my $queryID = $lineArray[0];
	my $subject = $lineArray[1];
	#print $queryID, " : ", $subject, "\n";
	$queryIDSubjectHash {$subject} = $queryID;
}

for my $subject (sort keys %matchHash) {
	my $queryID = $queryIDSubjectHash{$subject};
	#print "$subject => $queryID\n";
	my @matchArray = @{ $matchHash{$subject} };
	#print ($matchArray[0], ", ", $matchArray[1], ", ", $matchArray[2], 
	#		", ", $matchArray[3], ", ", $matchArray[4], "\n\n");
	push @{ $queriesCombinedHash {$queryID} }, $subject; 
}

for my $queryID (sort keys %queriesCombinedHash) {
	my @subjectIDs = @{ $queriesCombinedHash{$queryID} };
	#print "$queryID => @subjectIDs\n"; 
	print $queryID, "\n";
	foreach my $subjectID (@subjectIDs) {
		print $subjectID, "\n";
		my ($querySeq, $querySeqStart, $querySeqEnd) = @{ $matchHash{$subjectID} };
		foreach (my $i = 1; $i < ($querySeqStart - length($querySeqStart)); $i++) {
			print " ";
		}
		print $querySeqStart, $querySeq, $querySeqEnd, "\n";
	}
	print $subjectSeqHash{$queryID}, "\n\n";
}


print "\n\n";

# close open files
close(PRI);
close(BLAST);
close(TABLE);

# done
